from rest_framework.permissions import DjangoModelPermissions
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import status

from apps.orders.models import OrderInfo
from apps.meiduo_admin.serializers.order import OrderInfoSerializer
from apps.meiduo_admin.utils import PageNum


class OrderInfoView(ModelViewSet):
    """订单页面展示"""

    permission_classes = [DjangoModelPermissions]

    def get_queryset(self):
        # 获取前端传入的参数keyword。来判断是否为查询
        keyword = self.request.query_params.get('keyword')
        if keyword:
            queryset = OrderInfo.objects.filter(order_id__contains=keyword).order_by('create_time')
        else:
            # 获取订单数据
            queryset = OrderInfo.objects.all().order_by('create_time')

        return queryset
    # 指定序列化器
    serializer_class = OrderInfoSerializer
    # 指定分页器
    pagination_class = PageNum

    # 在视图中定义status方法修改订单状态(路由：orders/(?P<order_id>\d+)/status/)
    @action(methods=['PUT'], detail=True)
    def status(self, request, pk):
        # 获取要修改的数据
        order = self.get_object()
        # 获取要修改的状态值
        statu = request.data.get('status')
        # 判断状态值是否存在
        if statu not in [1, 2, 3, 4, 5]:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 修改订单状态
        order.status = statu
        order.save()
        # 返回结果
        return Response({
            'order_id': order.order_id,
            'status': order.status
        })



